﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using UFIDA.U9.Cust.STR.PlugBE.Public.Dto;
using UFSoft.UBF.Service;

namespace UFIDA.U9.Cust.STR.PlugBE.Public
{
    public class HttpHelper
    {
        public string URL { get; set; }
        public string Content { get; set; }
        public Dictionary<string, string> Header { get; set; } = new Dictionary<string, string>();
        public string ContentType = "application/json";
        public string Request(string postType = "POST")
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"请求地址:{URL}");
            var request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = postType;
            request.ContentType = ContentType;//ContentType
            foreach (var item in Header)
            {
                request.Headers.Add(item.Key, item.Value);
            }
            if (postType != "GET")
            {
                sb.AppendLine("请求参数:" + Content);
                byte[] byteData;
                if (ContentType == "application/x-www-form-urlencoded")
                {
                    byteData = Encoding.ASCII.GetBytes(Content);
                }
                else
                {
                    byteData = Encoding.UTF8.GetBytes(Content);
                }
                int length = byteData.Length;
                request.ContentLength = length;
                Stream writer = request.GetRequestStream();
                writer.Write(byteData, 0, length);
                writer.Close();
            }

            try
            {
                var response = (HttpWebResponse)request.GetResponse();
                var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
                sb.AppendLine($"返回值:{responseString}");
                LogManager.WriteLog(sb.ToString(), "AllRequest");
                return responseString;
            }
            catch (Exception e)
            {
                sb.AppendLine($"{e.Message}\r\n{e.StackTrace}");
                LogManager.WriteLog(sb.ToString(), "All");
                throw new Exception(e.Message);
            }
        }

        private Dictionary<string, object> OARegist(string APPID, string address)
        {
            // 获取当前系统RSA加密的公钥
            var rsa = new RSACryptoServiceProvider();
            var publicKey = Convert.ToBase64String(rsa.ExportCspBlob(false));
            var privateKey = Convert.ToBase64String(rsa.ExportCspBlob(true));

            // 调用ECOLOGY系统接口进行注册
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("appid", APPID);
                client.DefaultRequestHeaders.Add("cpk", publicKey);
                var response = client.PostAsync(address + "/api/ec/dev/auth/regist", null).Result;
                var data = response.Content.ReadAsStringAsync().Result;
                // 打印ECOLOGY响应信息
                LogManager.WriteLog($"请求地址:{address}/api/ec/dev/auth/regist", "OAAuth");
                LogManager.WriteLog($"返回值: {data}", "OAAuth");
                var datas = JsonConvert.DeserializeObject<Dictionary<string, object>>(data);
                return datas;
            }
        }

        /// <summary>
        /// 获取OA的token
        /// </summary>
        //public void OAGetToken()
        //{
        //    Header = new Dictionary<string, string>();
        //    JsonConfig _config = new JsonConfig();
        //    var APPID = _config.SelectToken("OA.APPID");
        //    var OAUrl = _config.SelectToken("OA.URL");
        //    // 从系统缓存或者数据库中获取ECOLOGY系统公钥和Secret信息
        //    var datas = OARegist(APPID, OAUrl);
        //    var secret = datas.ContainsKey("secrit") ? datas["secrit"].ToString() : null;
        //    var spk = datas.ContainsKey("spk") ? datas["spk"].ToString() : null;

        //    // 公钥加密,所以RSA对象私钥为null
        //    using (var rsa = new RSACryptoServiceProvider())
        //    {
        //        //ImportPublicKey(rsa,spk);
        //        var keyBytes = Base64.Decode(spk);
        //        var asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);
        //        var rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
        //        var rsaParameters = new RSAParameters
        //        {
        //            Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned(),
        //            Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned()
        //        };
        //        rsa.ImportParameters(rsaParameters);

        //        var encryptSecret = Convert.ToBase64String(rsa.Encrypt(Encoding.UTF8.GetBytes(secret), false));

        //        // 调用ECOLOGY系统接口进行注册
        //        using (var client = new HttpClient())
        //        {
        //            client.DefaultRequestHeaders.Add("appid", APPID);
        //            client.DefaultRequestHeaders.Add("secret", encryptSecret);
        //            client.DefaultRequestHeaders.Add("time", "3600");
        //            var response = client.PostAsync(OAUrl + "/api/ec/dev/auth/applytoken", null).Result;
        //            var data = response.Content.ReadAsStringAsync().Result;
        //            LogManager.WriteLog($"请求地址:{OAUrl}/api/ec/dev/auth/applytoken", "OAAuth");
        //            LogManager.WriteLog($"secret:{encryptSecret}", "OAAuth");
        //            LogManager.WriteLog($"返回值: {data}", "OAAuth");
        //            datas = JsonConvert.DeserializeObject<Dictionary<string, object>>(data);
        //            if (datas["code"].ToString() == "0")
        //            {
        //                var encryptUserid = Convert.ToBase64String(rsa.Encrypt(Encoding.UTF8.GetBytes("1"), false));
        //                Header.Add("appid", APPID);
        //                Header.Add("token", datas["token"].ToString());
        //                Header.Add("userid", encryptUserid);
        //            }
        //            else
        //            {
        //                throw new Exception(datas["msg"].ToString());
        //            }
        //        }
        //    }
        //}

        /// <summary>
        /// OA采购商场认证信息
        /// </summary>
        public OAItemAddPara.Header OAPurMallToken()
        {
            var result = new OAItemAddPara.Header();
            JsonConfig _config = new JsonConfig();
            //时间
            var currentDateTime = DateTime.Now.ToString("yyyyMMddHHmmss");
            result.currentDateTime = currentDateTime;
            var systemid = _config.SelectToken("OA.systemid");
            var password = _config.SelectToken("OA.password");
            result.systemid = systemid;
            //MD5
            string md5Source = systemid + password + currentDateTime;
            string md5 = PublicMethod.ComputeMD5Hash(md5Source);
            result.Md5 = md5;
            return result;
        }

    }
}
